<?php

namespace app\api\controller\order;

use app\api\controller\Controllers;
use app\api\service\foods\Foods;
use app\api\service\order\ShoppingCart as ShoppingCartService;
use app\api\model\order\ShoppingCart as ShoppingCartModels;
use app\api\service\system\System;

class ShoppingCart extends Controllers
{
    /**
     * 添加购物车
     *
     * @return \think\Response
     */
    public function add(Foods $foodsService, ShoppingCartService $service, System $system)
    {
        if ( false === $system->rest() ) {
            return failed('商家已休息');
        }
        $post = $this->request->only(['fid'], 'post');
        $foods = $foodsService->get($post['fid']);
        if ( $foods->stock <= 0 ) {
            return failed('库存不足');
        }
        $shopping = $service->get($post['fid']);
        $update = (false === $shopping->isEmpty());
        if ( $update && $shopping->number+1 > $foods->stock ) {
            return failed('库存不足');
        }
        return $service->save($post['fid'], $update, $shopping)?
            success():
            failed('添加购物车失败');
    }

    /**
     * 减少购物车
     *
     * @return \think\Response
     */
    public function reduce(int $id, ShoppingCartService $service)
    {
        return $service->reduce($id)?
            success():
            failed('购物车删减失败');
    }

    /**
     * 清空购物车
     *
     * @return \think\Response
     */
    public function clean(ShoppingCartService $service)
    {
        return $service->clean()?
            success():
            failed('清空失败或购物车无物品');
    }

    /**
     * 购物车列表
     *
     * @return \think\Response
     */
    public function cart(ShoppingCartService $service)
    {
        $lists = $service->cart();
        $price = array_sum(array_map(function($v){
            return $v['number']*$v['foods']['price'];
        }, $lists->toArray()));
        return success([
            'lists' => $lists,
            'price' => $price
        ]);
    }



}
